Exploring Common java.lang Classes in Java
Course: Core Java Training
Topic: Exploring Common java.lang Classes
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to the java.lang Package
The java.lang package is one of the most fundamental packages in Java. It contains classes and interfaces that support everyday programming tasks, including string handling, mathematical calculations, object management, primitive type wrappers, exception handling, and thread execution.
Java automatically makes the java.lang package available to every Java source file. Therefore, you can use classes such as String, Math, System, Object, and Integer without explicitly importing them.
Example
public class Main {
public static void main(String[] args) {
String name = "Java";
int number = 25;
int result = Math.max(number, 10);
System.out.println("Language: " + name);
System.out.println("Maximum value: " + result);
}
}
Output:
Language: Java
Maximum value: 25
In this example, String, Math, and System are used directly without import statements.
2. Learning Objectives
After completing this topic, you should be able to:
- Understand the purpose of the
java.lang package.
- Explain the functionality of commonly used classes.
- Use
String and StringBuilder for text processing.
- Use
Math for mathematical operations.
- Work with wrapper classes such as
Integer, Double, and Boolean.
- Understand the role of
Object and System.
- Recognize the purpose of
Class, Throwable, and Thread.
- Apply common classes in practical Java programs.
3. Overview of Common java.lang Classes
| Class |
Purpose |
Common Use |
Object |
Root superclass of Java classes |
Object comparison and representation |
String |
Represents immutable character sequences |
Names, messages, and text processing |
StringBuilder |
Creates mutable character sequences |
Repeated string modifications |
StringBuffer |
Provides a synchronized mutable character sequence |
String modification when synchronized operations are needed |
Math |
Provides mathematical methods and constants |
Rounding, powers, square roots, and trigonometry |
System |
Provides access to system-related facilities |
Console output, time measurement, and properties |
Integer |
Wraps an int value |
Parsing and converting integers |
Double |
Wraps a double value |
Parsing and converting decimal values |
Character |
Wraps a char value |
Character classification and conversion |
Boolean |
Wraps a boolean value |
Representing true or false as an object |
Class |
Represents runtime class information |
Inspecting class names and metadata |
Throwable |
Base class for errors and exceptions |
Understanding and handling exceptional conditions |
Thread |
Represents a thread of execution |
Concurrent task execution |
4. Understanding the Object Class
The Object class is the root of the Java class hierarchy. Classes that do not explicitly extend another class implicitly extend Object. As a result, its methods are available to objects throughout Java.
Important Object Methods
| Method |
Description |
toString() |
Returns a string representation of an object. |
equals(Object obj) |
Checks logical equality according to the implementation. |
hashCode() |
Returns an integer hash code for an object. |
getClass() |
Returns the runtime class of an object. |
notify() |
Wakes one thread waiting on that object's monitor. |
notifyAll() |
Wakes all threads waiting on that object's monitor. |
wait() |
Causes the current thread to wait until notified or interrupted, subject to its overload's behavior. |
Example: Using Object Methods
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student(101, "Aarav");
System.out.println(student.toString());
System.out.println(student.getClass().getName());
}
}
Output:
Student{id=101, name='Aarav'}
Student
Explanation: The toString() method is overridden to provide a meaningful description of a student. The getClass() method provides runtime class information.
Important Note About equals() and hashCode()
If you override equals() to define logical equality, you should also override hashCode(). Equal objects must return the same hash code. This is especially important when objects are stored in hash-based collections such as HashSet and HashMap.
5. Understanding the String Class
The String class represents a sequence of characters. Strings are widely used for storing names, addresses, messages, identifiers, and other text data.
Key Feature: String Immutability
Strings are immutable, which means their contents cannot be changed after a string object is created. Operations such as toUpperCase() and replace() return a result rather than modifying the original string.
Common String Methods
| Method |
Purpose |
Example |
length() |
Returns the number of UTF-16 code units |
"Java".length() returns 4 |
charAt(index) |
Returns the character at an index |
"Java".charAt(0) returns 'J' |
toUpperCase() |
Converts letters to uppercase |
"java".toUpperCase() |
toLowerCase() |
Converts letters to lowercase |
"JAVA".toLowerCase() |
equals() |
Compares string contents |
"Java".equals("Java") |
equalsIgnoreCase() |
Compares text without case sensitivity |
"JAVA".equalsIgnoreCase("java") |
contains() |
Checks whether a sequence is present |
"Core Java".contains("Java") |
substring() |
Extracts part of a string |
"Programming".substring(0, 7) |
trim() |
Removes leading and trailing characters with code points at or below U+0020 |
" Java ".trim() |
strip() |
Removes leading and trailing Unicode whitespace |
" Java ".strip() |
replace() |
Replaces matching characters or sequences |
"Java".replace('a', 'o') |
split() |
Splits a string using a regular expression |
"red,blue".split(",") |
Example: String Operations
public class Main {
public static void main(String[] args) {
String language = " Java Programming ";
System.out.println(language.trim());
System.out.println(language.toUpperCase());
System.out.println(language.contains("Java"));
System.out.println(language.strip().substring(0, 4));
}
}
Output:
Java Programming
JAVA PROGRAMMING
true
Java
Explanation: Each operation returns a result. The original language variable still refers to its original string.
Comparing Strings Correctly
String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);
System.out.println(first.equals(second));
Output:
false
true
The == operator compares object references for these string variables, while equals() compares the string contents. Use equals() when checking whether two strings contain the same text.
6. StringBuilder and StringBuffer
When a program needs to modify text repeatedly, StringBuilder and StringBuffer can be more suitable than creating many intermediate String objects.
StringBuilder
StringBuilder is a mutable sequence of characters. It is commonly used when one thread builds or modifies a string, especially inside loops.
public class Main {
public static void main(String[] args) {
StringBuilder message = new StringBuilder("Hello");
message.append(" Java");
message.insert(5, " from");
message.replace(0, 5, "Welcome");
System.out.println(message);
}
}
Output:
Welcome from Java
StringBuffer
StringBuffer provides mutable string operations with synchronized methods. It can be useful when synchronized access to the same buffer is needed, although synchronization alone does not automatically make a larger multi-step operation logically thread-safe.
Comparison
| Feature |
String |
StringBuilder |
StringBuffer |
| Mutable |
No |
Yes |
Yes |
| Methods synchronized |
Not applicable to content modification |
No |
Yes, for its synchronized methods |
| Typical use |
Fixed text |
Repeated text construction |
Mutable text with synchronized method access |
| Common methods |
substring(), contains() |
append(), insert(), delete() |
append(), insert(), delete() |
7. Understanding the Math Class
The Math class provides static methods and constants for common mathematical operations. Because its methods are static, you call them using the class name rather than creating a Math object.
Common Math Methods
| Method or Constant |
Purpose |
Example |
Math.max(a, b) |
Returns the larger value |
Math.max(10, 20) returns 20 |
Math.min(a, b) |
Returns the smaller value |
Math.min(10, 20) returns 10 |
Math.abs(x) |
Returns the absolute value |
Math.abs(-12) returns 12 |
Math.sqrt(x) |
Calculates the square root |
Math.sqrt(64) returns 8.0 |
Math.pow(a, b) |
Raises a value to a power |
Math.pow(2, 3) returns 8.0 |
Math.ceil(x) |
Rounds toward positive infinity |
Math.ceil(4.2) returns 5.0 |
Math.floor(x) |
Rounds toward negative infinity |
Math.floor(4.8) returns 4.0 |
Math.round(x) |
Rounds to the nearest integer type for the overload |
Math.round(4.6) returns 5 |
Math.random() |
Returns a pseudorandom double from 0.0 inclusive to 1.0 exclusive |
Math.random() |
Math.PI |
Approximation of pi |
Math.PI |
Example: Mathematical Calculations
public class Main {
public static void main(String[] args) {
int a = -15;
int b = 8;
System.out.println("Absolute value: " + Math.abs(a));
System.out.println("Maximum: " + Math.max(a, b));
System.out.println("Square root: " + Math.sqrt(81));
System.out.println("Power: " + Math.pow(2, 4));
System.out.println("Rounded value: " + Math.round(6.7));
System.out.println("Pi: " + Math.PI);
}
}
Output:
Absolute value: 15
Maximum: 8
Square root: 9.0
Power: 16.0
Rounded value: 7
Pi: 3.141592653589793
Important Points
- Most
Math methods are static and are called through Math.
Math.sqrt() returns NaN for a negative finite argument.
Math.random() is not suitable for security-sensitive random values. Use java.security.SecureRandom for such cases.
- For financial calculations that require decimal precision, consider
java.math.BigDecimal and appropriate rounding rules.
8. Wrapper Classes in Java
Wrapper classes represent primitive values as objects. They are useful when an API requires an object, when working with generic types and collections, and when converting between textual and numeric representations.
Primitive Types and Their Wrapper Classes
| Primitive Type |
Wrapper Class |
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
char |
Character |
boolean |
Boolean |
Integer Class
The Integer class wraps an int value and provides methods for parsing, conversion, comparison, and numeric limits.
public class Main {
public static void main(String[] args) {
int number = Integer.parseInt("250");
Integer value = Integer.valueOf(100);
System.out.println(number + 50);
System.out.println(value);
System.out.println(Integer.MAX_VALUE);
}
}
Output:
300
100
2147483647
Double Class
The Double class represents a double value as an object and offers methods for parsing and converting decimal values.
public class Main {
public static void main(String[] args) {
double price = Double.parseDouble("199.50");
Double discount = Double.valueOf(20.0);
System.out.println("Price: " + price);
System.out.println("Discount: " + discount);
System.out.println("Final price: " + (price - discount));
}
}
Output:
Price: 199.5
Discount: 20.0
Final price: 179.5
Character Class
The Character class includes static methods for checking and converting individual characters.
public class Main {
public static void main(String[] args) {
char letter = 'A';
char digit = '7';
System.out.println(Character.isLetter(letter));
System.out.println(Character.isDigit(digit));
System.out.println(Character.toLowerCase(letter));
}
}
Output:
true
true
a
Boolean Class
The Boolean class represents a boolean value as an object. Its parseBoolean() method returns true only when the supplied string equals "true", ignoring case. Other strings, including null, result in false.
public class Main {
public static void main(String[] args) {
boolean active = Boolean.parseBoolean("true");
boolean another = Boolean.parseBoolean("yes");
System.out.println(active);
System.out.println(another);
}
}
Output:
true
false
9. Autoboxing and Unboxing
Java supports automatic conversion between primitive values and their corresponding wrapper objects. These conversions are known as autoboxing and unboxing.
- Autoboxing: Converting a primitive value into its wrapper object.
- Unboxing: Converting a wrapper object into its primitive value.
public class Main {
public static void main(String[] args) {
int primitive = 50;
Integer objectValue = primitive; // Autoboxing
int result = objectValue; // Unboxing
System.out.println(objectValue);
System.out.println(result);
}
}
Output:
50
50
Important: Unboxing a null wrapper reference throws NullPointerException. Check nullable wrapper values before unboxing them.
10. Understanding the System Class
The System class provides access to standard input and output streams, error output, system properties, environment information, time-related methods, and other system facilities.
Common System Members
| Member |
Purpose |
System.out |
Standard output stream |
System.err |
Standard error output stream |
System.in |
Standard input stream |
System.currentTimeMillis() |
Returns the current time in milliseconds since the Unix epoch |
System.nanoTime() |
Provides a high-resolution time source for measuring elapsed time |
System.getProperty() |
Reads a system property |
System.getenv() |
Reads an environment variable |
System.exit() |
Requests termination of the running JVM |
System.arraycopy() |
Copies elements between arrays |
Example: System Class Methods
public class Main {
public static void main(String[] args) {
System.out.println("Java program started");
String os = System.getProperty("os.name");
System.out.println("Operating system: " + os);
long start = System.nanoTime();
int total = 0;
for (int i = 1; i <= 1000; i++) {
total += i;
}
long elapsed = System.nanoTime() - start;
System.out.println("Total: " + total);
System.out.println("Elapsed nanoseconds: " + elapsed);
}
}
Explanation: The operating system name is retrieved through a system property. The elapsed time is measured with nanoTime(); the exact duration varies by execution and environment.
Best Practices
- Use
System.out.println() for simple console output and debugging.
- Use a proper logging framework for application logging in larger projects.
- Use
System.nanoTime() for elapsed-time measurements rather than subtracting wall-clock timestamps.
- Avoid using
System.exit() inside reusable library code because it can terminate the entire JVM process.
- Do not assume environment variables or system properties always exist; handle missing values appropriately.
11. Understanding the Class Class
The Class class represents classes and interfaces at runtime. It supports reflection, allowing programs to inspect information such as class names, methods, fields, and constructors.
Getting a Class Object
public class Main {
public static void main(String[] args) {
String text = "Java";
Class<?> classInfo = text.getClass();
System.out.println(classInfo.getName());
System.out.println(classInfo.getSimpleName());
}
}
Output:
java.lang.String
String
Another way to obtain class information is by using a class literal, such as String.class.
Class<String> stringClass = String.class;
System.out.println(stringClass.getSimpleName());
Output:
String
Where Class Is Useful
- Inspecting runtime type information.
- Supporting dependency injection and frameworks.
- Discovering methods and fields through reflection.
- Working with annotations and runtime metadata.
Reflection should be used thoughtfully because it can make code harder to understand and may be restricted by access controls or module boundaries.
12. Understanding Throwable, Exception, and Error
Throwable is the superclass of Java objects that can be thrown and caught. Its two major branches are Error and Exception.
- Error: Represents serious conditions that applications generally should not attempt to handle as ordinary recoverable problems.
- Exception: Represents conditions that an application may be able to handle.
- RuntimeException: A subclass of
Exception that includes unchecked exceptions such as NullPointerException and IllegalArgumentException.
Example: Handling an Exception
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
System.out.println("Reason: " + e.getMessage());
}
}
}
Output:
Cannot divide by zero.
Reason: / by zero
Useful Throwable Methods
| Method |
Purpose |
getMessage() |
Returns the detail message, if present. |
toString() |
Returns a concise description of the throwable. |
printStackTrace() |
Prints stack-trace information to the error stream by default. |
getCause() |
Returns the underlying cause, if present. |
Best practice: Catch exceptions that your program can meaningfully handle. Avoid catching every exception without an appropriate recovery strategy, and do not use exceptions as a substitute for ordinary control flow.
13. Introduction to the Thread Class
The Thread class represents a thread of execution. Java applications can use multiple threads to perform tasks concurrently. A thread may be created by extending Thread or, more commonly for simple tasks, by passing a Runnable to a thread.
Example: Creating a Thread with Runnable
public class Main {
public static void main(String[] args) {
Runnable task = () -> {
System.out.println("Task running in a separate thread");
};
Thread worker = new Thread(task);
worker.start();
System.out.println("Main method continues");
}
}
Important: The order of the two printed messages can vary because the main thread and worker thread may be scheduled in different orders. Calling start() begins a new thread of execution; calling run() directly does not start a separate thread.
Common Thread Methods
| Method |
Purpose |
start() |
Starts a thread. |
run() |
Contains the task executed by the thread. |
sleep() |
Pauses the current thread for a specified time, subject to scheduling. |
join() |
Waits for another thread to finish. |
isAlive() |
Checks whether a thread has started and has not yet terminated. |
currentThread() |
Returns a reference to the currently executing thread. |
14. Practical Program Using Multiple java.lang Classes
The following example combines string processing, wrapper classes, mathematical calculations, and system output in a single program.
public class JavaLangDemo {
public static void main(String[] args) {
String studentName = " Priya Sharma ";
String cleanName = studentName.strip();
Integer marks = Integer.parseInt("85");
Double bonus = Double.valueOf(5.5);
double total = marks + bonus;
System.out.println("Student: " + cleanName);
System.out.println("Name length: " + cleanName.length());
System.out.println("Marks: " + marks);
System.out.println("Bonus: " + bonus);
System.out.println("Total: " + total);
System.out.println("Rounded total: " + Math.round(total));
System.out.println("Runtime class: " + marks.getClass().getName());
}
}
Sample Output:
Student: Priya Sharma
Name length: 12
Marks: 85
Bonus: 5.5
Total: 90.5
Rounded total: 91
Runtime class: java.lang.Integer
Explanation: The program cleans a string, converts text to numeric wrapper values, performs a calculation, rounds the result, and inspects the runtime class of an object.
15. Common Mistakes and Troubleshooting
| Problem |
Reason |
Solution |
Using == to compare string content |
It compares references for object variables. |
Use equals() for content comparison. |
| Expecting a String method to modify the original string |
String is immutable. |
Store the returned string or use a mutable builder. |
| Parsing invalid numeric text |
The input does not represent a valid number. |
Validate the input and handle NumberFormatException. |
| Unboxing a null wrapper |
The wrapper reference has no value object. |
Check for null before unboxing. |
| Assuming random values are secure |
Math.random() is not designed for security-sensitive randomness. |
Use SecureRandom where appropriate. |
| Expecting a fixed output order from threads |
Thread scheduling is nondeterministic. |
Use synchronization or coordination mechanisms when order matters. |
Calling run() expecting a new thread |
A direct call executes as a normal method call. |
Call start() to start a new thread. |
Trying to import java.lang unnecessarily |
The package is available automatically. |
Use common classes directly without an import statement. |
16. Best Practices for Using java.lang Classes
- Use the appropriate class for each task instead of writing utility logic from scratch.
- Use
String for immutable text and StringBuilder for repeated text modifications.
- Use
equals() to compare object contents when the class defines the desired equality behavior.
- Override
toString() for meaningful object descriptions when useful.
- Override
equals() and hashCode() consistently when defining logical equality.
- Use wrapper parsing methods carefully and validate untrusted input.
- Use
Math methods for common calculations and understand their return types.
- Use
System.nanoTime() for elapsed-time measurement.
- Handle exceptions specifically and avoid swallowing errors silently.
- Use threads only when concurrency is needed, and coordinate shared mutable data safely.
17. Practice Exercises
- String Processing: Create a program that accepts a name and prints its trimmed value, uppercase value, and character count.
- Math Operations: Write a program that calculates the square root, absolute value, and maximum of given numbers.
- Wrapper Classes: Convert numeric strings into
Integer and Double values and calculate their sum.
- Object Methods: Create a
Book class and override toString() to display its title and author.
- System Properties: Print the Java version using
System.getProperty("java.version").
- Exception Handling: Parse a numeric string and handle invalid input with
NumberFormatException.
- StringBuilder: Build a comma-separated list of five programming languages using a loop.
- Thread Basics: Create a
Runnable that prints a short message several times, then start it using a Thread.
18. Mini Project: Student Result Calculator
Objective: Build a simple console program that demonstrates multiple classes from java.lang.
Requirements
- Store a student's name in a
String.
- Parse marks from a numeric string using
Integer.parseInt().
- Calculate a percentage or adjusted score using arithmetic operations.
- Use
Math.round() to display a rounded score.
- Use
System.out.println() to display the result.
- Handle invalid numeric input with an appropriate exception handler.
Sample Implementation
public class StudentResult {
public static void main(String[] args) {
String name = " Rohan ".strip();
String marksInput = "78";
try {
int marks = Integer.parseInt(marksInput);
double percentage = (marks / 100.0) * 100;
long rounded = Math.round(percentage);
System.out.println("Student: " + name);
System.out.println("Marks: " + marks);
System.out.println("Percentage: " + percentage + "%");
System.out.println("Rounded percentage: " + rounded + "%");
} catch (NumberFormatException e) {
System.out.println("Please provide valid numeric marks.");
}
}
}
Expected Output:
Student: Rohan
Marks: 78
Percentage: 78.0%
Rounded percentage: 78%
This example uses a simplified score out of 100. Extend it to accept marks from multiple subjects, calculate totals and averages, validate the allowed range, and assign grades.
19. Interview Questions and Answers
Q1. What is the java.lang package?
Answer: It is a core Java package that contains fundamental classes and interfaces, including String, Object, Math, System, wrapper classes, and exception-related types. It is automatically available to Java source files.
Q2. Why is the Object class important?
Answer: It is the root superclass of the Java class hierarchy and defines common methods such as toString(), equals(), hashCode(), and getClass().
Q3. Why are String objects immutable?
Answer: Immutability supports safe sharing of string values and helps with predictable behavior. Operations that appear to change a string return a new result instead of changing the existing string's contents.
Q4. What is the difference between StringBuilder and StringBuffer?
Answer: Both are mutable character sequences. StringBuilder does not synchronize its methods, while StringBuffer provides synchronized methods.
Q5. What is the purpose of the Math class?
Answer: It provides static methods and constants for common mathematical calculations, such as square roots, powers, rounding, and trigonometric operations.
Q6. What is a wrapper class?
Answer: A wrapper class represents a primitive value as an object. For example, Integer wraps an int, and Double wraps a double.
Q7. What are autoboxing and unboxing?
Answer: Autoboxing automatically converts a primitive value to its corresponding wrapper object. Unboxing converts the wrapper object back to its primitive value.
Q8. What is the difference between == and equals()?
Answer: For object references, == checks whether the references identify the same object. equals() checks logical equality as defined by the class.
Q9. What is the purpose of the System class?
Answer: It provides standard input and output streams, system properties, environment access, time-related methods, array copying, and other system facilities.
Q10. What is the Class class used for?
Answer: It represents runtime class information and supports reflection, which allows programs to inspect class metadata.
Q11. What is Throwable?
Answer: It is the superclass of all Java errors and exceptions that can be thrown and caught.
Q12. What is the difference between start() and run()?
Answer: Calling start() starts a new thread of execution, which then invokes run(). Calling run() directly executes the method on the current thread.
20. Quick Revision Checklist
- Understand why
java.lang is automatically available.
- Know that
Object is the root superclass of Java classes.
- Remember that
String is immutable.
- Know when to use
StringBuilder or StringBuffer.
- Practice common
Math methods.
- Recognize all eight primitive-wrapper class pairs.
- Understand autoboxing and unboxing.
- Use
System methods appropriately.
- Understand the purpose of
Class and runtime type information.
- Recognize the relationship between
Throwable, Exception, and Error.
- Know the basic difference between starting a thread and calling its run method.
21. Conclusion
The java.lang package provides many of the building blocks used in everyday Java development. Classes such as String, Object, Math, System, wrapper classes, Class, Throwable, and Thread help developers manage text, calculations, objects, system interactions, type conversions, exceptions, and concurrent execution.
Learning these classes makes Java programs easier to write, read, debug, and maintain. Practice the examples and exercises in this lesson, then explore the official API documentation for more details about individual methods.
Continue Learning: Explore the Core Java Training Course, register for a course demo, or visit the JustAcademy website.